﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.DomainModel;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Web;
using MethodWorx.CMS.Providers;
using MethodWorx.CMS.Requests;

namespace MethodWorx.CMS.Services
{
    public class ContentTemplateService
    {
        private IContentTemplateRepository contentTemplates;
        private IUnitOfWorkFactory unitOfWorkFactory;

        public ContentTemplateService(ICmsDataProvider provider)
            : this(provider.GetUnitOfWorkFactory(), 
                   provider.GetService<IContentTemplateRepository>())
        {
        }

        public ContentTemplateService(IUnitOfWorkFactory unitOfWorkFactory, IContentTemplateRepository contentTemplates)
        {

            if (contentTemplates == null)
                throw new ArgumentNullException("contentTemplates");

            if (unitOfWorkFactory == null)
                throw new ArgumentNullException("unitOfWorkFactory");

            this.unitOfWorkFactory = unitOfWorkFactory;
            this.contentTemplates = contentTemplates;
        }


        public void UpdateContentTemplateBasicDetails(UpdateContentTemplateBasicDetailsRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            using (var uow = this.unitOfWorkFactory.Begin())
            {
                uow.RegisterChanged(request.ContentTemplate);
                uow.Commit();
            }
        }


        public void UpdateContentTemplateProperties(UpdateContentTemplatePropertiesRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            using (var unitOfWork = this.unitOfWorkFactory.Begin())
            {
                unitOfWork.RegisterChanged(request.ContentTemplate);
                unitOfWork.Commit();
            }
        }

        public virtual ContentTemplate GetContentTemplateById(Guid id)
        {
            return this.contentTemplates[id];
        }

        public virtual ContentTemplate CreateEntityInstance()
        {
            return this.contentTemplates.CreateEntityInstance();
        }
    }
}
